package wang.aweb.childcar.util;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;
import wang.aweb.childcar.tcpserver.ServerHandler;

import java.util.Date;
import java.util.Map;

public class SendMsgUtils {
    public static boolean sendToDevice(String channelId,String msg){
        Boolean flag=false;

        for(Map.Entry<ChannelId,ChannelHandlerContext> entry:ServerHandler.CHANNEL_MAP.entrySet() ){
            if(entry.getValue().channel().id().toString().equals(channelId)){
                entry.getValue().writeAndFlush(msg);
                flag=true;
            }
        }

        return flag;
    }
    public static String makeTcpMsg(String mingling,String imei,String zhiling){
        String returnStr="4253"+mingling;
        String mingLing=String2Hex(imei)+getHexTime()+zhiling;
        String mLen=fullZero(4,Integer.toHexString(mingLing.length()/2));
        returnStr=returnStr+mLen+mingLing;
        String sign=getSign(returnStr);
        returnStr=returnStr+sign;
        return returnStr;
    }
    private static String getSign(String code){
        int y=0;
        for(int i=0;i<code.length();i+=2){
            y=y^Integer.parseInt(code.substring(i,i+2),16);
        }

        String res=decHex(y);
        if(res.length()==1){
            res="0"+res;
        }
        return res;
    }
    /**
     * 十六进制转十进制
     * @param num
     * @return
     */
    private static String decHex(int num){
        char[] map = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
        if(num == 0) return "0";
        String result = "";
        while(num != 0){
            int x = num&0xF;
            result = map[(x)] + result;
            num = (num >>> 4);
        }
        return result;
    }
    private static String fullZero(Integer len,String str){
        Integer count=len-str.length();
        String zeroStr="";
        for(int i=0;i<count;i++){
            zeroStr=zeroStr+"0";
        }
        return zeroStr+str;
    }
    /**
     * 获取16进制的时间戳
     * @return 返回16进制的时间戳
     */
    private static String getHexTime(){
        String timestamp=String.valueOf(new Date().getTime());
        String sjc=timestamp.substring(0,timestamp.length()-3);
        return Integer.toHexString(Integer.valueOf(sjc));
    }

    /**
     * 字符串转16进制
     * @param str
     * @return 实际是12345 to 3132333435
     */
    private static String String2Hex(String str){
        String retStr="";
        for(int i=0;i<str.length();i++){
            retStr=retStr+"3"+str.substring(i,i+1);
        }
        return retStr;
    }
}
